<template>
	<view class="chart-cont">
		<l-echart class="chart" ref="chartRef" :customStyle="customStyle"></l-echart>
		<!-- <l-echart class="chart" ref="chartRef"></l-echart> -->
	</view>
</template>
<script setup lang="ts">
	import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
	const echarts = require('../../../uni_modules/lime-echart/static/echarts.min');
	const { proxy } = getCurrentInstance();

	const props = defineProps({
		chartData: Object,
		type: Array,
	});

	defineExpose({
		initChart
	})

	const chartRef = ref(null);
	const myChart = ref(null);
	const xData = ref([]);
	const yData = ref([]);
	const customStyle = ref({
		height: "130px"
	});

	var data = [];
	var dataCount = 20;
	var startTime = +new Date();
	var categories = [];
	var types = ref([])
	// var types = ref([{ name: '化霜', color: '#BCCAFA', type: "0" },
	// { name: '制冷', color: '#99F0EB', type: "1" },
	// { name: '待机', color: '#D2D2D2', type: "2" }]);
	// Generate mock data
	categories.forEach(function (category, index) {
		var baseTime = startTime;
		for (var i = 0; i < dataCount; i++) {
			// console.log(types.value)
			if (types.value && types.value.length) {
				var typeItem = types.value[Math.round(Math.random() * (types.value.length - 1))];
				var duration = Math.round(Math.random() * 10000 * 1000);
				data.push({
					name: typeItem.name,
					value: [index, baseTime, (baseTime += duration), duration, typeItem.name],
					itemStyle: { normal: { color: typeItem.color } }
				});
				baseTime += Math.round(Math.random() * 2000);
			}
		}
	});
	function renderItem(params, api) {

		var categoryIndex = api.value(0);
		var start = api.coord([api.value(1), categoryIndex]);
		var end = api.coord([api.value(2), categoryIndex]);
		var height = api.size([0, 1])[1] * 0.6;
		var rectShape = echarts.graphic.clipRectByRect(
			{
				x: start[0],
				y: start[1] - height / 2,
				width: end[0] - start[0],
				height: height
			}
			,
			{
				x: params.coordSys.x,
				y: params.coordSys.y,
				width: params.coordSys.width,
				height: params.coordSys.height
			}
		);
		return (
			rectShape && {
				type: 'rect',
				name: api.value(4),
				transition: ['shape'],
				shape: rectShape,
				style: api.style()
			}
		);
	}
	const option = reactive({
		tooltip: {
			position: function (pos, params, dom, rect, size) {
				// 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
				var obj = { top: '20%' };
				obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
				return obj;
			},
			hideDelay: 100,
			// trigger: 'item',
			padding: [0, 10],
			formatter: function (params) {
				return params.marker + params.name + '\n' +
					'开始时间:' + formate(params.value[1]) + '\n' +
					'结束时间:' + formate(params.value[2]) + '\n' +
					'持续时长:' + getDuration(params.value[3]);
			}
		},
		// legend: {
		// 	left: "center",
		// 	itemWidth: 10,
		// 	itemHeight: 5,
		// 	data: ['化霜', '制冷', '待机']
		// },
		title: {
			show: false
		},
		dataZoom: [
			// {
			// 	type: 'slider',
			// 	filterMode: 'weakFilter',
			// 	showDataShadow: true,
			// 	top: 300,
			// 	labelFormatter: ''
			// },
			{
				type: 'inside',
				filterMode: 'weakFilter'
			}
		],
		grid: {
			top: 90,
			left: '10%',
			right: '10%',
			height: 15,
			width: '80%'
		},
		xAxis: {
			min: startTime,
			max: startTime,
			scale: true,
			// show: false,
			splitNumber: 3,
			axisTick: {
				show: false,

			},
			axisLabel: {
				formatter: function (val) {
					return proxy.dayjs(val).format('HH:mm:ss');
				}
			}
		},
		yAxis: {
			data: categories,
			show: false,
		},
		series: [
			{
				type: 'custom',
				renderItem: renderItem,
				itemStyle: {
					opacity: 0.8
				},
				encode: {
					x: [1, 2],
					y: 0,
				},
				data: data
			}
		]
	});


	/* 刷新数据 */
	uni.$on('stat-initChart', () => {
		initChart()
	})

	onMounted(() => {
		// 组件能被调用必须是组件的节点已经被渲染到页面上
		// setTimeout(() => {
		// initChart()
		// }, 1000)
	});

	async function initChart() {
		types.value = props.type;

		if (props.chartData && props.chartData.stat && props.chartData.stat.length) {
			data = [];
			for (var index = 0; index < props.chartData.stat.length; index++) {
				let category = props.chartData.stat[index];
				
				
				var typeItem = types.value[category.key];
				typeItem = types.value.filter(item => {
					return item.type == category.key
				})[0]
				


				let noRepeat = true;
				for (let i = data.length - 1; i >= 0; i--) {
					if (data[i].value[1] == category.data[0] && data[i].value[2] == category.data[1]) {
						if (data[i].value[5] == "key_2") {
							data.splice(i, 1);
						} else {
							noRepeat = false;
						}
					}
				}

				if (noRepeat) {
					data.push({
						name: typeItem.name,
						value: [index, category.data[0], category.data[1], category.data[2], typeItem.name, typeItem.type],
						itemStyle: { normal: { color: typeItem.color } }
					});
				}


			}
			

			option.xAxis.min = props.chartData.stat[0].data[0]
			option.xAxis.max = props.chartData.stat[props.chartData.stat.length - 1].data[1]

			option.yAxis.data = [props.chartData.name]
			option.series[0].data = data
		}


		// console.log("initChart 2 props.chartData", props.chartData, data);

		if (!chartRef.value) return
		const chart = await chartRef.value.init(echarts)
		chart.setOption(option)
		myChart.value = chart
	}

	function formate(val) {
		return proxy.dayjs(val).format('HH:mm:ss');
	}
	function getDuration(millis) {
		// let seconds = Math.ceil(val / 1000);
		// let minutes = Math.ceil(seconds / 60);
		// let hours = Math.ceil(minutes / 60);
		// // 计算剩余的分钟和秒
		// const remainingMinutes = minutes % 60;
		// const remainingSeconds = seconds % 60;


		let hours = Math.floor(millis / 3600000);
		let minutes = Math.floor((millis % 3600000) / 60000);
		let seconds = Math.floor((millis % 60000) / 1000);
		let millisecondsLeft = Math.floor(millis % 1000);

		let time;
		if (hours > 0) {
			time = `${hours}小时${minutes}分钟${seconds}秒`
		} else if (minutes > 0) {
			time = `${minutes}分钟${seconds}秒`
		} else {
			time = `${seconds}秒`
		}
		return time;
	}
</script>
<style lang="scss" scoped>
	.chart-cont {
		position: relative;
		width: 100%;
		height: 100%;
		overflow: visible !important;

		.chart {
			width: 100%;
			height: 100% !important;
			/* 或者设置为 auto, visible-x, visible-y 等 */
			overflow: visible !important;
		}
	}
</style>